#!/bin/bash

# 日志函数（带时间戳和级别）
log() {
    local level="$1"
    local message="$2"
    printf "%s|%-4s| %s\n" "$(date +'%Y/%m/%d %H:%M:%S.000')" "$level" "$message"
}

WORKSPACE=$(dirname "$0")
LUBAN_DLL="$WORKSPACE/../../Tools/Luban/Luban.dll"
CUSTOM_TEMPLATES="$WORKSPACE/../../Tools/CustomTemplates"
VALIDATION_PATH="$WORKSPACE"

# 参数处理（带默认值）
DOTNET_PATH="${1:-dotnet}"

log INFO "=========================================================================================="
log INFO "Starting configuration validation"
log INFO "-- Workspace:   $WORKSPACE"
log INFO "-- Luban DLL:   $LUBAN_DLL"
log INFO "-- Templates:   $CUSTOM_TEMPLATES"

# 检查关键文件是否存在
if [[ ! -f "$LUBAN_DLL" ]]; then
    log ERROR "Luban.dll not found at $LUBAN_DLL"
    exit 1
fi

if [[ ! -f "$WORKSPACE/luban.conf" ]]; then
    log ERROR "Configuration file $WORKSPACE/luban.conf not found"
    exit 1
fi

log CONFG "Using .NET runtime: $DOTNET_PATH"
log DEBUG "Validation command:"
log DEBUG "-- $DOTNET_PATH $LUBAN_DLL"
log DEBUG "-- conf $WORKSPACE/luban.conf"
log DEBUG "-- customTemplateDir $CUSTOM_TEMPLATES"
log DEBUG "-- validationFailAsError -t all -f"

# 执行验证命令
log INFO "=========================================================================================="
log INFO "Running Luban validation..."

$DOTNET_PATH $LUBAN_DLL \
    --conf "$WORKSPACE/luban.conf" \
    --customTemplateDir "$CUSTOM_TEMPLATES" \
    --validationFailAsError true \
    -t all \
    -f

VALIDATION_EXIT=$?
log INFO "------------------------------------------------------------------------------------------"
log INFO "Validation process finished with exit code: $VALIDATION_EXIT"

if [[ $VALIDATION_EXIT -eq 0 ]]; then
    log SUCCESS "=========================================================================================="
    log SUCCESS "Validation successful! All configurations are valid."
    log SUCCESS "=========================================================================================="
    exit 0
else
    log ERROR "=========================================================================================="
    log ERROR "Validation failed! Please check the error messages above."
    log ERROR "=========================================================================================="
    exit $VALIDATION_EXIT
fi